<?php
    include_once '../connection/databaseHandler.php';
    include_once '../connection/sessionHandler.php';
    $database = new DatabaseHandler();
    $session = new SessionHandler();

    // menghilangkan kemungkinan SQL Injection
    $to = stripslashes($_POST['message_to']);
    $subject = stripslashes($_POST['message_subject']);
    $content = stripslashes($_POST['message_content']);
    $to = mysql_escape_string($to);
    $subject = mysql_escape_string($subject);
    $content = mysql_escape_string($content);

    $username = $session->username;
    $date = date("Y-m-d");

    $query="SELECT * FROM ".$database->t_user." WHERE username='".$to."'";
    $result = $database->execQuery($query);
    $count = mysql_num_rows($result);
    if ($count!=1) {
        header("location:../profile.php?id=".$username."&page=new-message");
    }
    else {
    // mengisi database komentar
    $query = "INSERT INTO $database->t_message (
                id,
                username,
                content,
                subject,
                date
            ) VALUES (
                NULL,
                '$username',
                '$content',
                '$subject',
                '$date'
            )";

    $database->execQuery($query);

    $query = "INSERT INTO $database->t_messagefor (
                id_message,
                to_username
            ) VALUES (
                LAST_INSERT_ID(),
                '$to'
            )";

    $database->execQuery($query);
    header("location:../profile.php?id=".$username."&page=message&n=1");
    }
?>
